# vim:ts=4:sw=4:noet:
""" Manager for long running tasks (compilation, etc) """

import threading
import logging

class TaskManager:
	def __init__(self, mc):
		self.mc = mc
		self.tasks = {}
	
	def __del__(self):
		logging.info("[tm] killing old threads for shutdown")
		for t in self.tasks:
			self.stopTask(t)
				
	def hasTask(self, name):
		return ((name in self.tasks) and self.tasks[name].isAlive())

	def createTask(self, name, workFunc, workFuncArgs=[], start=True, daemon=False):
		if name in self.tasks:
			task = self.tasks[name]
			logging.info("[tm] killing old task '%s'" % name)
			if task.isAlive():
				task.join()
		self.tasks[name] = threading.Thread(
				None,
				self._make_task_wrapper(workFunc, workFuncArgs))
		if daemon:
			self.tasks[name].setDaemon(True)
		if start:
			self.startTask(name)

	def _make_task_wrapper(self, workFunc, workFuncArgs):
		def _task_wrapper():
			try:
				workFunc(*workFuncArgs)
			except Exception,e:
				self.mc.handleThreadException(e)
		return _task_wrapper

	def startTask(self, name):
		logging.info("[tm] starting task '%s' (%s)" % (name, 
				" ".join([t for t in self.tasks if self.tasks[t].isAlive()])))
		self.tasks[name].start()

	def stopTask(self, name):
		if name in self.tasks:
			task = self.tasks[name]
			if task.isAlive():
				logging.info("[tm] stopping task '%s'" % name)
				task.join()

